
import BASE_URL from './env'

export default {
	request(options) {
		return new Promise((resolve, reject) => {
			let url = options.url;
			if (!(url.indexOf("http://") !== -1 || url.indexOf("https://") !== -1)) {
				options.url = BASE_URL + "/weapp/" + url;
			}
			// 携带请求头
			options.header = {
				'Content-Type': 'application/json',
				...options.header,
			}
			options.header.token = uni.getStorageSync("token") ?? "";
			options.complete = (response) => {
				if (response.statusCode == 200 || response.statusCode == 0) {
					if (response.data.code == 401 || response.data.code == 420) {
						uni.setStorageSync("token", "");
						uni.navigateTo({
							url: "/pages/login/login",
						});
					}
					if (response.data.code == 500) {
						uni.showToast({
							title: response.data.msg,
							icon: "none",
							duration: 2000,
						});
					}
					resolve(response.data);
				} else {
					uni.showToast({
						title: "请求异常",
						icon: "none",
					});
				}
			};
			uni.request(options);
		});
	},

	post(url, data = {}, header = {}) {
		let options = {
			url: url,
			data: data,
			header: header,
			method: "POST",
		};

		return this.request(options);
	},

	get(url, data = {}, header = {}) {
		let options = {
			url: url,
			data: data,
			header: header,
		};

		return this.request(options);
	},
}